package com.pn.controller;

import com.pn.entity.Result;
import com.pn.model.*;
import com.pn.page.Page;
import com.pn.service.*;
import com.pn.utils.CurrentUser;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import io.netty.util.internal.ResourcesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/product")
@RestController
public class ProductController {

    @Autowired
    private StoreService storeService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductTypeService ProductTypeService;

    @Autowired
    private SupplyService supplyService;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private UnitService unitService;

    @Value("${file.upload-path}")
    private String uploadPath;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 查询所有仓库
     * @return
     */
    @RequestMapping("/store-list")
    public Result storeList(){
        //执行业务
        List<Store> storeList = storeService.queryAllStore();
        //响应
        return Result.ok(storeList);
    }

    /**
     * 查询所有品牌
     * @return
     */
    @RequestMapping("/brand-list")
    public Result brandList(){
        //执行业务
        List<Brand> brandList = brandService.queryAllBrand();
        //响应
        return Result.ok(brandList);
    }

    /**
     * 分页查询商品
     * @param page
     * @param product
     * @return
     */
    @RequestMapping("/product-page-list")
    public Result productListPage(Page page, Product product){
        //执行业务
        page = productService.queryProductPage(page,product);
        //响应
        return Result.ok(page);
    }

    /**
     * 查询所有商品目录分类树
     * @return
     */
    @RequestMapping("/category-tree")
    public Result loadTypeTree(){
        //执行业务
        List<ProductType> typeTreeList = ProductTypeService.productTypeTree();
        //响应
        return Result.ok(typeTreeList);
    }

    /**
     * 查询所有供应商
     * @return
     */
    @RequestMapping("/supply-list")
    public Result supplyList(){
        //执行业务
        List<Supply> supplyList = supplyService.queryAllSupply();
        //响应
        return Result.ok(supplyList);
    }

    /**
     * 查询所有产地
     * @return
     */
    @RequestMapping("/place-list")
    public Result placeList(){
        //执行业务
        List<Place> placeList = placeService.queryAllPlace();
        //响应
        return Result.ok(placeList);
    }

    /**
     * 查询所有单位
     * @return
     */
    @RequestMapping("/unit-list")
    public Result unitList(){
        //执行业务
        List<Unit> unitList = unitService.queryAllUnit();
        //响应
        return Result.ok(unitList);
    }

    /**
     * 上传图片
     * 参数MultipartFile file ---表示封装了请求参数叫file的上传的图片
     * file.transferTo(上传的文件保存到的磁盘文件的File对象)--实现文件的上传
     * @param file
     * @return
     */
    @CrossOrigin//表示这个接口允许被跨域请求
    @RequestMapping("/img-upload")
    public Result uploadImage(MultipartFile file){

        try{
             /*
         拿到图片上传到的目录路径的File对象---classpath:static/img/upload
         因为图片上传到的目录是个类路径（resources下的路径/classes下的路径，就是待遇前缀classpath），
         所以不能直接将路径封装到File对象；使用类路径资源工具类ResourceUtils的刚发getFile（）来解析类路径
         并拿到封装了类路径的File对象
         */
            File uploadDirFile = ResourceUtils.getFile(uploadPath);
            //拿到图片上传到的目录路径的磁盘路径
            String uploadDirPath = uploadDirFile.getAbsolutePath();
            //拿到上传的图片的名称
            String fileName = file.getOriginalFilename();
            //拿到上传的文件要保存到的磁盘文件的路径
            String uploadFilePath = uploadDirPath + "\\" + fileName;
            //上传图片
            file.transferTo(new File(uploadFilePath));
            //成功响应
            return Result.ok("图片上传成功！");
        }catch (Exception e){
            return Result.err(Result.CODE_ERR_BUSINESS,"图片上传失败！");
        }

    }

    @RequestMapping("/product-add")
    public Result addProduct(@RequestBody Product product, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        //拿到当前登录用户的id
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int createBy = currentUser.getUserId();

        product.setCreateBy(createBy);

        //执行业务
        Result result = productService.saveProduct(product);
        //响应
        return result;
    }

    /**
     * 修改商品上下架状态
     * @param product
     * @return
     */
    @RequestMapping("/state-change")
    public Result changeProduceState(@RequestBody Product product){
        //执行业务
        Result result = productService.updateStateByPid(product);
        //响应
        return result;
    }

    /**
     * 删除单个商品
     * @param productId
     * @return
     */
    @RequestMapping("/product-delete/{productId}")
    public Result deleteProduct(@PathVariable int productId){
        //执行业务
        Result result = productService.deleteProductByIds(Arrays.asList(productId));
        //响应
        return result;
    }

    /**
     * 删除多个商品
     * @param productIdList
     * @return
     */
    @RequestMapping("/product-list-delete")
    public Result deleteProductList(@RequestBody List<Integer> productIdList){
        //执行业务
        Result result = productService.deleteProductByIds(productIdList);
        //响应
        return result;
    }

    @RequestMapping("/product-update")
    public Result updateProduct(@RequestBody Product product,@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        //拿到当前登录用户的id
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int updateBy = currentUser.getUserId();
        product.setUpdateBy(updateBy);

        //执行业务
        Result result = productService.setProductById(product);
        //响应
        return result;
    }



}
